package com.qtenv.datasync.worker.huizhong;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qtenv.datasync.api.huizhong.GetMethodsServiceLocator;
import com.qtenv.datasync.base.DataSyncer;
import com.qtenv.datasync.constant.AppConstants;
import com.qtenv.datasync.service.entity.TerminalHistoryData;
import com.qtenv.datasync.service.entity.Terminals_bf;
import com.qtenv.datasync.service.entity.huizhong.HZTerminalHistoryData;
import com.qtenv.datasync.service.service.TerminalsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName HZDataSyncWorker
 * @Author CBL
 * @Date 2022/2/24 14:52
 **/
@Component
public class HZDataSyncWorker extends DataSyncer {
    @Autowired
    private TerminalsService terminalsService;

    // NB表
    private final String TYPE_NB = "11000005";
    private GetMethodsServiceLocator hzService = new GetMethodsServiceLocator();

    public HZDataSyncWorker() {
        super("汇中");
    }

    @Override
    public List<TerminalHistoryData> getTerminalHistoryData(String tenantId, String strStartTime, String strEndTime) {
        List<Terminals_bf> terminalsList = terminalsService.findMasTerminalsByTenantAndSupplier(tenantId, AppConstants.HZ_SUPPLIER_ID);
        return this.doGetTerminalHistoryData(tenantId, terminalsList, strStartTime, strEndTime);
    }

    @Override
    public List<TerminalHistoryData> getTerminalHistoryDataForTerminal(Terminals_bf terminals, String tenantId, String strStartTime, String strEndTime) {
        return super.getTerminalHistoryDataForTerminal(terminals, tenantId, strStartTime, strEndTime);
    }

    @Override
    public List<TerminalHistoryData> getTerminalHistoryData(String tenantId, List<String> terminalIdList, String strStartTime, String strEndTime) {
        List<Terminals_bf> terminalsList = terminalsService.list(new QueryWrapper<Terminals_bf>().in("TerminalID", terminalIdList));
        if (CollectionUtil.isNotEmpty(terminalsList)) {
            terminalsList.forEach(item -> item.setTerminalID(item.getTerminalID().substring(10)));
        }
        return this.doGetTerminalHistoryData(tenantId, terminalsList, strStartTime, strEndTime);
    }

    public List<TerminalHistoryData> doGetTerminalHistoryData(String tenantId, List<Terminals_bf> terminalsList, String strStartTime, String strEndTime) {
        List<TerminalHistoryData> result = CollectionUtil.newArrayList();
        if (CollectionUtil.isNotEmpty(terminalsList)) {
            LocalDate now = LocalDate.now();
            String startTime = (strStartTime == null ? now.toString() + " 00:00:00" : strStartTime);
            String endTime = (strEndTime == null ? now.toString() + " 23:59:59" : strEndTime);

            Map<String, List<Terminals_bf>> terminalListByModuleType = terminalsList.stream().collect(Collectors.groupingBy(Terminals_bf::getModuleType));

            JSONArray pageArray = new JSONArray();
            terminalListByModuleType.keySet().forEach(key -> {
                List<Terminals_bf> tmpTerminalList = terminalListByModuleType.get(key);
                String meterCode = tmpTerminalList.stream().map(Terminals_bf::getTerminalID).collect(Collectors.joining(","));
                // NB表不需要分页取数据
                if (key.equals(TYPE_NB)) {
                    try {
                        String pageData = hzService.getGetMethods().getNBHistoryData(AppConstants.HZ_ZC_TENANT_ID, meterCode, startTime, endTime);
                        if (StrUtil.isNotEmpty(pageData)) {
//                            System.out.println(pageData);
                            JSONArray nbJsonArray = JSON.parseArray(JSON.parseObject(pageData).getString(AppConstants.HZ_DATA_KEY));
//                            System.out.println("NB表共：" + nbJsonArray.size() + "条数据");
                            pageArray.addAll(nbJsonArray);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    } catch (ServiceException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        String strPage = hzService.getGetMethods().getHistoryDataCount(AppConstants.HZ_ZC_TENANT_ID, meterCode, startTime, endTime);
                        JSONObject objPage = JSON.parseObject(strPage);
                        if (objPage.getIntValue("success") == 0) {
//                            int total = objPage.getIntValue("total");
//                            System.out.println("非NB表共：" + total + "条数据");
                            int pages = objPage.getIntValue("pages");
//                            System.out.println("共：" + pages + "页");
                            int pageSize = objPage.getIntValue("pageSize");
//                            System.out.println("每页：" + pageSize + "条数据");

                            for (int pageIndex = 1; pageIndex <= pages; pageIndex++) {
                                String pageData = hzService.getGetMethods().getHistoryData(AppConstants.HZ_ZC_TENANT_ID, meterCode, startTime, endTime, String.valueOf(pageIndex), String.valueOf(pageSize));
                                if (StrUtil.isNotEmpty(pageData)) {
//                                    System.out.println(pageData);
                                    pageArray.addAll(JSON.parseArray(JSON.parseObject(pageData).getString(AppConstants.HZ_DATA_KEY)));
                                }
                            }
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    } catch (ServiceException e) {
                        e.printStackTrace();
                    }
                }
            });

            if (pageArray.size() > 0 && StrUtil.isNotEmpty(pageArray.toJSONString())) {
                List<TerminalHistoryData> tmpList = this.transform(tenantId, pageArray.toJSONString());
                if (CollectionUtil.isNotEmpty(tmpList)) {
                    result.addAll(tmpList);
                }
            }
        }

        return result;
    }


    private List<TerminalHistoryData> transform(String tenantId, String strData) {
        List<TerminalHistoryData> result = CollectionUtil.newArrayList();

        List<HZTerminalHistoryData> hzTerminalHistoryDataList = JSON.parseArray(strData, HZTerminalHistoryData.class);
        hzTerminalHistoryDataList.forEach(hzTerminalHistoryData -> {
            TerminalHistoryData terminalHistoryData = new TerminalHistoryData();
            BeanUtil.copyProperties(hzTerminalHistoryData, terminalHistoryData);
            terminalHistoryData.setTenant_id(tenantId);
            terminalHistoryData.setSupplierID(AppConstants.HZ_SUPPLIER_ID);
            if (terminalHistoryData.getTotalFlow() == null) {
                terminalHistoryData.setTotalFlow(terminalHistoryData.getReadNumber().subtract(terminalHistoryData.getReverseNumber()));
            }

            result.add(terminalHistoryData);
        });

        return result;
    }

    @Override
    public List<TerminalHistoryData> doGetTerminalHistoryDataFromTerminal(Terminals_bf terminals, String tenantId, String tids, String strStartTime, String strEndTime) {
        return super.doGetTerminalHistoryDataFromTerminal(terminals, tenantId, tids, strStartTime, strEndTime);
    }

    @Override
    public List<TerminalHistoryData> transformFromTerminal(Terminals_bf terminals, String tenantId, String strData) {
        return super.transformFromTerminal(terminals, tenantId, strData);
    }

    public static void main(String[] args) {
//        HZDataSyncWorker worker = new HZDataSyncWorker();
//        System.out.println(JSON.toJSONString(worker.getTerminalHistoryData("2022-03-17 00:00:00", "2022-03-17 23:59:59"), true));

        // 汇中数据接口拉取当天数据-有数据

//        String sp = " 00:00:00";
//        LocalDate s = LocalDate.parse("2022-06-17");
//        String ep = " 23:59:59";
//        LocalDate e = LocalDate.parse("2022-06-22");
//        while (s.isBefore(e) || s.isEqual(e)) {
//            worker.syncTerminalHistoryData(s.toString() + sp, s.toString() + ep);
//            s = s.plusDays(1L);
//        }
    }
}
